package com.lzp.java.concurrent.lock.readwritelock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 测试读写锁插队策略
 *
 * @author lzp
 * @date 2020/04/13
 */
public class JumpQueueStrategy {
    /**
     * 定义读写锁 true为公平锁，不可以插队
     */
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(false);
    private static ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
    private static ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();

    public static void read() {
        System.out.println(Thread.currentThread().getName() + "尝试获取读锁");
        readLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取到读锁，开始读取");
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(Thread.currentThread().getName() + "读取完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    public static void write() {
        System.out.println(Thread.currentThread().getName() + "尝试获取写锁");
        writeLock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "获取到写锁，开始写入");
            TimeUnit.MILLISECONDS.sleep(20);
            System.out.println(Thread.currentThread().getName() + "写入完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        new Thread(() -> write(), "写线程1").start();
        new Thread(() -> read(), "读线程1").start();
        new Thread(() -> read(), "读线程2").start();
        new Thread(() -> write(), "写线程2").start();
        new Thread(() -> read(), "读线程3").start();
        new Thread(() -> {
            Thread[] threads = new Thread[1000];
            for (int i = 0; i < 1000; i++) {
                threads[i] = new Thread(() -> read(), "插队线程" + i);
            }
            for (int i = 0; i < 1000; i++) {
                threads[i].start();
            }
        }).start();
    }

}
